package logic

import (
	"context"
	"errors"
	"zg2/zk1_user/userRpc/cache"
	"zg2/zk1_user/userRpc/models"

	"zg2/zk1_user/userRpc/internal/svc"
	"zg2/zk1_user/userRpc/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *user.LoginRequest) (*user.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var ur models.User
	ur.Mobile = in.Mobile

	if err = ur.GetUserByMobile(); err != nil {
		logx.Error("用户信息获取失败")
		return nil, errors.New("用户信息获取失败")
	}

	if ur.ID == 0 {
		if err = ur.Register(); err != nil {
			logx.Error("用户创建失败")
			return nil, errors.New("用户创建失败")
		}
	}

	sms, err := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if err != nil {
		return nil, err
	}
	if sms != in.SmsCode {
		logx.Error("短信验证码错误")
		return nil, errors.New("短信验证码错误")
	}

	return &user.LoginResponse{
		Id: int64(ur.ID),
	}, nil
}
